<template>
  <div class="container">
    <h2 class="title">添加销售订单</h2>
    <form @submit.prevent="handleSubmit" class="form">
      <div class="form-group">
        <label for="customer" class="label">客户:</label>
        <select
            id="customer"
            v-model="order.customer"
            required
            class="input"
        >
          <option value="">请选择客户</option>
          <option v-for="customer in customers" :key="customer.id" :value="customer.id">{{
              customer.customer_name
            }}
          </option>
        </select>
      </div>

      <div class="form-group">
        <label class="label">商品明细:</label>
        <div class="sales-detail-item">
          <div class="form-inline">
            <div class="form-group" style="flex: 1; margin-right: 10px;">
              <label>商品:</label>
              <select v-model="order.sales_detail.goods" @change="getGoodsPrice" class="input">
                <option value="">请选择商品</option>
                <option v-for="good in goodsList" :key="good.id" :value="good.id">{{ good.goods_name }}</option>
              </select>
            </div>
            <div class="form-group" style="flex: 1; margin-right: 10px;">
              <label>数量:</label>
              <input type="number" v-model="order.sales_detail.quantity" @input="calculateTotal" required
                     class="input"/>
            </div>
            <div class="form-group" style="flex: 1;">
              <label>单价:</label>
              <input type="number" v-model="order.sales_detail.unit_price" readonly class="input"/>
            </div>
          </div>
        </div>
      </div>

      <div class="form-group">
        <label for="total_amount" class="label">总金额:</label>
        <input
            type="number"
            id="total_amount"
            v-model="order.total_amount"
            readonly
            class="input"
        />
      </div>

      <div class="form-actions">
        <button type="submit" class="button submit-btn">提交</button>
        <button type="button" @click="handleCancel" class="button cancel-btn">取消</button>
      </div>
    </form>
  </div>
</template>

<script>
import {createSalesOrder} from '@/api/salesOrders';
import {getGoods} from '@/api/goods';
import {getCustomers} from '@/api/customers'; // 引入获取客户列表的 API
import {ref, onMounted} from 'vue';
import {useRouter} from 'vue-router';

export default {
  setup() {
    const router = useRouter();
    const order = ref({
      customer: '',
      total_amount: 0,
      sales_detail: {
        goods: null,
        quantity: null,
        unit_price: null
      }
    });
    const goodsList = ref([]);
    const customers = ref([]); // 存储客户列表

    // 获取商品列表
    // 获取商品列表并筛选已上架的商品
    const fetchGoodsList = async () => {
      try {
        const allGoods = await getGoods();
        // 筛选状态为已上架的商品
        goodsList.value = allGoods.filter(good => good.on_shelves);
      } catch (error) {
        console.error('Error fetching goods list:', error);
        goodsList.value = []; // 如果请求失败，设置为空数组
      }
    };

    // 获取客户列表
    const fetchCustomers = async () => {
      try {
        const response = await getCustomers();
        customers.value = response.data;
      } catch (error) {
        console.error('Error fetching customers:', error);
      }
    };

    // 根据商品 ID 获取商品单价
    const getGoodsPrice = () => {
      if (order.value.sales_detail.goods) {
        const selectedGood = goodsList.value.find(good => good.id === parseInt(order.value.sales_detail.goods));
        if (selectedGood) {
          order.value.sales_detail.unit_price = parseFloat(selectedGood.price);
          calculateTotal();
        }
      } else {
        order.value.sales_detail.unit_price = null;
        order.value.total_amount = 0;
      }
    };

    // 计算总金额
    const calculateTotal = () => {
      if (order.value.sales_detail.unit_price && order.value.sales_detail.quantity) {
        order.value.total_amount = order.value.sales_detail.unit_price * order.value.sales_detail.quantity;
      } else {
        order.value.total_amount = 0;
      }
    };

    const handleSubmit = async () => {
      try {
        if (!order.value.sales_detail.goods || !order.value.sales_detail.quantity) {
          alert('请选择商品并输入数量');
          return;
        }

        await createSalesOrder(order.value);
        router.push('/sales/orders');
      } catch (error) {
        if (error.response && error.response.data.error) {
          alert(error.response.data.error); // 显示后端返回的错误信息
        } else {
          console.error('Error creating sales order:', error);
          alert('创建销售订单失败');
        }
      }
    };

    // 取消按钮的逻辑
    const handleCancel = () => {
      router.push('/sales/orders'); // 返回销售订单列表
    };


    onMounted(() => {
      fetchGoodsList();
      fetchCustomers(); // 在组件挂载时获取客户列表
    });

    return {
      order,
      goodsList,
      customers, // 返回客户列表
      handleSubmit,
      getGoodsPrice,
      calculateTotal,
      handleCancel
    };
  }
};
</script>

<style scoped>
.container {
  max-width: 800px;
  margin: 2rem auto;
  padding: 2rem;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.title {
  color: #333;
  margin-bottom: 1.5rem;
  text-align: center;
}

.form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.label {
  font-weight: 500;
  color: #555;
}

.input {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
}

.input:focus {
  border-color: #007bff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.form-inline {
  display: flex;
  align-items: flex-end;
  gap: 1rem;
  margin-bottom: 1rem;
}

.form-actions {
  display: flex;
  gap: 1rem;
}

.button {
  padding: 0.8rem;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.submit-btn {
  width: 100%;
  background: #007bff;
  color: #fff;
}

.submit-btn:hover {
  background: #0056b3;
}

.cancel-btn {
  width: 100%;
  background: #6c757d;
  color: #fff;
}

.cancel-btn:hover {
  background: #5a6268;
}

@media (max-width: 480px) {
  .container {
    margin: 1rem;
    padding: 1.5rem;
  }

  .form-inline {
    flex-direction: column;
  }

  .form-actions {
    flex-direction: column;
  }
}
</style>
